package com.usefullc.english.service;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.english.domain.*;
import com.usefullc.english.enums.ContentStatusEnum;
import com.usefullc.english.param.ContentParam;
import com.usefullc.english.query.*;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.user.OnlineUser;
import com.usefullc.common.user.OnlineUserManager;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.english.mapper.ContentMapper;
import com.usefullc.english.vo.ContentVo;
import com.usefullc.common.util.RequestUtils;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.service.AbstractBizService;
import com.usefullc.system.validator.UsefulPropertyVerify;
import com.usefullc.system.vo.TreeVo;
import com.usefullc.user.domain.User;
import com.usefullc.user.service.UserService;
import com.usefullc.user.service.component.UserManager;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 内容服务类
 *
 * @author: 星空
 * @date: 2022-08-07
 */
@Service
public class ContentService extends AbstractBizService<ContentMapper, Content, ContentQuery> {


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContentReadService contentReadService;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private ReplyLikeService replyLikeService;

    @Autowired
    private ContentLikeService contentLikeService;

    @Autowired
    private ContentShareService contentShareService;

    @Autowired
    private TagService tagService;

    @Override
    protected QueryWrapper<Content> getQueryWrapper(ContentQuery query) {
        QueryWrapper<Content> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<ContentVo> findVoByPage(ContentQuery query) {
        Pager<Content> page = this.findByPage(query);
        Pager<ContentVo> newPage = new Pager<>(page);
        List<Content> dataList = page.getDataList();
        List<ContentVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (Content content : dataList) {
            ContentVo contentVo = BeanUtils.beanCopy(content, ContentVo.class);

            //标签
            List<Tag> tagList = tagService.getBaseMapper().findByContentId(content.getId());
            if (CollectionUtils.isNotEmpty(tagList)) {

                List<String> tags = tagList.stream().map(data -> data.getName()).collect(Collectors.toList());
                contentVo.setTags(tags);
            }

            newDataList.add(contentVo);
        }
        return newPage;
    }

    public Pager<ContentVo> findCmsVoByPage(ContentQuery query) {
        Pager<Content> page = this.findByPage(query);
        Pager<ContentVo> newPage = new Pager<>(page);
        List<Content> dataList = page.getDataList();
        List<ContentVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (Content content : dataList) {
            ContentVo contentVo = wrapperCmsContent(content);
            newDataList.add(contentVo);
        }
        return newPage;
    }

    public List<ContentVo> findCmsList(ContentQuery query) {
        List<Content> dataList = this.findAll(query);
        List<ContentVo> newDataList = new ArrayList<>();
        for (Content content : dataList) {
            ContentVo contentVo = wrapperCmsContent(content);
            newDataList.add(contentVo);
        }
        return newDataList;
    }

    public Pager<ContentVo> findCmsPageVoByTag(TagQuery query) {
        long total = this.baseMapper.findCountByTagId(query.getId());
        Pager<ContentVo> pager = new Pager<>(query.getPageIndex(), query.getPageSize(), total);
        if (total == 0) {
            return pager;
        }
        List<Content> dataList = this.baseMapper.findByTagId(query.getId(), pager);
        List<ContentVo> newDataList = new ArrayList<>();
        for (Content content : dataList) {
            ContentVo contentVo = wrapperCmsContent(content);
            newDataList.add(contentVo);
        }
        pager.setDataList(newDataList);
        return pager;
    }

    public ContentVo wrapperCmsContent(Content content) {
        if (content == null) {
            return null;
        }
        ContentVo contentVo = BeanUtils.beanCopy(content, ContentVo.class);
        //用户
        Long userId = content.getUserId();

        User user = userService.findById(userId);
        String author = "匿名";
        String avator = "";
        if (user != null) {
            author = user.getNickname();
            avator = user.getAvatar();
        }
        contentVo.setAuthor(author);
        contentVo.setAvatar(avator);

        //类目
        Category category = categoryService.findById(content.getCategoryId());
        contentVo.setCategory(category);

        return contentVo;

    }


    public List<TreeVo> listTree(ContentQuery query) {
        //获取类目
        List<TreeVo> categoryTreeList = categoryService.listTree(new CategoryQuery());


        //每个节点添加文章
        List<Content> contentList = this.findAll(query);
        Map<Long, List<Content>> contentMap = contentList.stream().collect(Collectors.groupingBy(data -> data.getCategoryId()));

        List<TreeVo> newTreeList = new ArrayList<>();
        wrapperLitTree(categoryTreeList, newTreeList, contentMap);

        return newTreeList;
    }

    private void wrapperLitTree(List<TreeVo> categoryTreeList, List<TreeVo> resultTreeList, Map<Long, List<Content>> contentMap) {
        for (TreeVo treeVo : categoryTreeList) {
            String key = treeVo.getKey();

            TreeVo newTreeVo = new TreeVo();
            newTreeVo.setTitle("[类目]" + treeVo.getTitle());
            newTreeVo.setKey("c" + treeVo.getKey());
            newTreeVo.setValue("c" + treeVo.getValue());
            resultTreeList.add(newTreeVo);

            List<TreeVo> newChildren = new ArrayList<>();
            newTreeVo.setChildren(newChildren);
            List<TreeVo> categoryTreeChildren = treeVo.getChildren();

            if (CollectionUtils.isNotEmpty(categoryTreeChildren)) {  //有子类目，再递归
                wrapperLitTree(categoryTreeChildren, newChildren, contentMap);
            }

            //每个类目去添加文章集合
            List<Content> childContentList = contentMap.get(Long.valueOf(key));
            if (CollectionUtils.isNotEmpty(childContentList)) {
                for (Content content : childContentList) {
                    TreeVo childTreeVo = new TreeVo();
                    newChildren.add(childTreeVo);
                    childTreeVo.setTitle("[文章]" + content.getTitle());
                    childTreeVo.setValue("a" + content.getId().toString());
                    childTreeVo.setKey("a" + content.getId().toString());
                }
            }
        }

    }

    @Transactional
    public Content saveContent(ContentParam param) {
        boolean result;
        Content entity;
        if (param.getId() == null) {
            entity = BeanUtils.beanCopy(param, Content.class);
            if (entity.getUserId() == null) {
                entity.setUserId(UserManager.getLoginUser().getId());
            }
            entity.setStatus(ContentStatusEnum.DRAFT.getCode());
            entity.setContribution(YesNoEnum.NO.getCode());
            entity.setLikeNum(0);
            entity.setReplyNum(0);
            entity.setReadNum(0);
            entity.setShareNum(0);
            this.save(entity);
            result = this.update(entity);
        } else {
            entity = this.findById(param.getId());
            BeanUtils.beanCopy(param, entity);
            result = this.update(entity);
        }

        //标签处理
        tagService.getBaseMapper().deleteContentTagByContentId(param.getId());

        List<String> tags = param.getTags();
        for (String tagName : tags) {
            Tag tag = tagService.findByTagName(tagName);
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setDescription(tagName);
            }
            tagService.save(tag);
            tagService.getBaseMapper().insertContentTag(entity.getId(), tag.getId());
        }
        return entity;
    }

    @Override
    public boolean save(Content entity) {
        super.save(entity);
        return super.update(entity);
    }

    @Override
    public boolean update(Content entity) {
        //设置url
        entity.setUrl("/cmsEnglish/content/" + entity.getId() + ".html");
        return super.update(entity);
    }

    public boolean doRead(Long contentId) {
        ContentRead contentRead = new ContentRead();
        contentRead.setContentId(contentId);
        HttpServletRequest request = RequestUtils.getRequest();
        String ip = RequestUtils.getClientIpAddr(request);
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if (loginUser != null) {
            contentRead.setUserId(loginUser.getUserId());
        }
        contentRead.setIp(ip);
        return contentReadService.save(contentRead);
    }

    public void updateActionNum() {
        //获取所有文章
        ContentQuery contentQuery = new ContentQuery();
        contentQuery.setStatus(ContentStatusEnum.RELEASED.getCode());
        List<Content> dataList = this.findAll(contentQuery);
        for (Content content : dataList) {
            Long contentId = content.getId();
            //获取文章的阅读数
            ContentReadQuery contentReadQuery = new ContentReadQuery();
            contentReadQuery.setContentId(content.getId());
            long readCount = contentReadService.count(contentReadQuery);

            //获取点赞数
            ContentLikeQuery contentLikeQuery = new ContentLikeQuery();
            contentLikeQuery.setContentId(content.getId());
            contentLikeQuery.setStatus(YesNoEnum.YES.getCode());
            long likeCount = contentLikeService.count(contentLikeQuery);

            //回复数量
            ReplyQuery replyQuery = new ReplyQuery();
            replyQuery.setContentId(content.getId());
            long replyCount = replyService.count(replyQuery);

            //分享数量
            ContentShareQuery contentShareQuery = new ContentShareQuery();
            contentShareQuery.setContentId(content.getId());
            long shareCount = contentShareService.count(contentShareQuery);


            //修改
            this.baseMapper.updateActionNum(contentId, readCount, likeCount, replyCount, shareCount);


        }

    }

    public void dataFix(){
        ContentQuery contentQuery = new ContentQuery();
//        contentQuery.setStatus(ContentStatusEnum.RELEASED.getCode());
        List<Content> dataList = this.findAll(contentQuery);
        for (Content content : dataList) {
            String videoUrl = content.getVideoUrl();
            Integer orderNo = 1;
            if(StringUtils.endsWith(videoUrl,".mp4")){
                int i = videoUrl.lastIndexOf("-");
                String orderNoStr = videoUrl.substring(i + 1, videoUrl.length() - 4);
                if(StringUtils.startsWith(orderNoStr,"0")){
                    orderNoStr = StringUtils.removeStart(orderNoStr,"0");
                }
                try{
                    orderNo = Integer.valueOf(orderNoStr);
                }catch (Exception e){
                }
            }
            content.setOrderNo(orderNo);
            this.save(content);
        }

    }

}
